﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Security.Principal;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;

namespace Noria.CFC
{
    class AppUtil
    {
        public static bool IsAdmin()
        {
            WindowsIdentity id = WindowsIdentity.GetCurrent();
            WindowsPrincipal p = new WindowsPrincipal(id);
            return p.IsInRole(WindowsBuiltInRole.Administrator);
        }

        public static void RunElevated(string file, string args)
        {
            var psi = new ProcessStartInfo();
            psi.Verb = "runas";
            psi.FileName = file;
            psi.Arguments = args;

            try
            {
                Process.Start(psi);
            }
            catch (Exception e)
            {
                var msg = "Faild to run elevated due to " + e.Message;
                MessageBox.Show(msg, "Register", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public static void Register()
        {
            var v = Application.ExecutablePath + " \"%1\"";
            Registry.SetValue(@"HKEY_CLASSES_ROOT\txtfile\shell\更改文字编码\command", "", v, RegistryValueKind.ExpandString);
        }

        public static string ReadFile(string file)
        {
            // TODO: better to check BOM
            //  currently, always read as GB2312 format
            return File.ReadAllText(file, Encoding.GetEncoding(936));
        }

        public static void SaveFile(string file, string content)
        {
            File.WriteAllText(file, content, Encoding.UTF8);
        }
    }
}
